import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Storage } from '@ionic/storage';
import { Headers, RequestOptions } from '@angular/http';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class HttpService
{
    //private domain = 'http://www.acishan.com/m';
    private domain = 'http://localhost/td/';
    public constructor(private http: Http, private storage: Storage) {}

    /**
     * HTTP POST
     * @param url
     * @param data
     * @param callback
     */
    public post(url, data = {}, callback) {
      this.storage.get('mytoken').then(token => {
        let body = ''

        for (let key in data) {
          body += key + '=' + data[key] + '&'
        }

        let headers = new Headers({
          'Content-Type': 'application/x-www-form-urlencoded'
        });

        let options = new RequestOptions({
          headers: headers
        });

        url = url.search(/http/) == 0 ? url : this.domain + url
        body = body.substring(0, body.length-1)
        this.http.post(url, body, options).toPromise().then(response => {
          try {
            callback(response)
          } catch (e) {
            console.log('response 回调错误: ' + e)
          }
        }, (error) => {
          return error.json().msg || 'Server error, please try again later'
        })
        console.log('request url: ' + url + ' body: ' + body)
      })
    }

  public get(url, callback) {
    this.storage.get('mytoken').then(token => {
      let headers = new Headers({
        'Content-Type': 'application/x-www-form-urlencoded'
      });

      let options = new RequestOptions({
        headers: headers
      });
      url = url.search(/http/) == 0 ? url : this.domain + url
      this.http.get(url, options).toPromise().then(response => callback(response), (error) => {
        return error.json().msg || 'Server error, please try again later'
      });
    })
  }
}
